#!/usr/bin/env python
#-*- coding:utf-8 -*-


'''
用户模块
author: cold night
email : coldnight.linux@gmail.com
'''

from model.get_db import get_db
from model.common import encrypt
from common import dict_to_sql
from common import format_result


conn = get_db()
cursor = conn.cursor()

__all__ = ['check_exists', 'check_user', 'check_shell', 'create_user', 'get_user']

def check_exists(username):
    '''
    判断要创建的用户是否存在
    返回True则表示用户存在
    返回False则表示用户不存在
    '''
    sql = 'select `username` from users WHERE `username`=%s'
    param = (username,)
    result = cursor.execute(sql, param)
    if (result):
        r = True
    else:
        r = False

    return r

def check_user(username, password):
    password = encrypt(password)
    sql = 'select `password` from users WHERE `username`=%s and `password`=%s'
    param = (username, password)
    result = cursor.execute(sql, param)
    if (result):
        r = True
    else:
        r = False
    return r


# 检验用户验证
def check_shell(user, shell):
    '''
    校验用户验证,shell是密码和用户名加上加密码验证得出
    比较COOKIE里和数据库里的校验是否相同
    user->用户名,必须
    shell-> cookie里的shell,必须
    返回True代表验证成功
    返回False代表验证失败
    '''

    if user and shell:
        # 获取密码
        sql = 'select `password` from users WHERE `username`=%s'
        param = (user,)
        r = cursor.execute(sql, param)
        passwd = cursor.fetchone()[0]

        # 加密后获取shell
        realshell = encrypt(user + passwd)
        # 比较shell
        if realshell == shell:
            return True
        else:
            return False
    else:
        return False


def create_user(user_dict):
    '''
    user_dict.keys():
    必须:
    username,
    password
    email,
    可选:
    nickname,
    role,
    '''
    if check_exists(user_dict.get('username')):
        return False
    passwd = user_dict.get('password')
    passwd = encrypt(passwd)
    user_dict['password'] = passwd
    sql = "INSERT INTO " + dict_to_sql('users', user_dict)
    r = cursor.execute(sql)
    conn.commit()
    return r



def get_user(_id):
    keys = ['username', 'password', 'nickname', 'email',
            'date', 'role', 'picture', 'lastlogin', 'lasttime']
    sql = 'select * from users WHERE `_id`=%s'
    param = (_id,)
    cursor.execute(sql, param)
    r = cursor.fetchone()
    result = format_result(r, keys)

    if not result.get('nickname'):
        result['nickname'] = result.get('username')
    return result
